package com.situ.mall.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.situ.mall.common.entity.Attachment;
import com.situ.mall.common.entity.Member;
import com.situ.mall.common.mapper.AttachmentMapper;
import com.situ.mall.common.mapper.MemberMapper;
import com.situ.mall.common.service.IAttachmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwj
 * @since 2023-09-13
 */
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IAttachmentService {

    @Value("${file.path}")
    private String filePath;
    @Value("${file.location}")
    private String fileLocation;

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private AttachmentMapper attachmentMapper;



    @Override
    public ResultVO upload(MultipartFile file) {
        ResultVO res=new ResultVO();
        String newFileName =System.currentTimeMillis()+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            File f = new File(fileLocation + newFileName);
            file.transferTo(f);
            res.setData(fileLocation+newFileName);
            Member m = (Member) RequestUtil.getCurrent();
            m.setAvatar(filePath+newFileName);
            memberMapper.updateById(m);
            res.setData(m);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("上传文件失败");
        }
        return res;

    }



    @Override
    public void bind(String attIds, Integer id, String source) {
        attachmentMapper.bind(attIds.split(","),id,source);
    }

    @Override
    public void clean() {
        System.out.println("service 去清理了");
    }

    @Override
    public List<Attachment> selectList(String source, Integer id) {

        return baseMapper.selectList(new LambdaQueryWrapper<Attachment>().eq(Attachment::getSource, source).eq(Attachment::getSourceId, id));
    }


}
